package com.sign2024.sign2024project.reporttest.controller;


import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.write.metadata.style.WriteCellStyle;
import com.alibaba.excel.write.metadata.style.WriteFont;
import com.alibaba.excel.write.style.HorizontalCellStyleStrategy;
import com.sign2024.sign2024core.common.utils.StringUtils;
import com.sign2024.sign2024project.reporttest.ReportTest;
import com.sign2024.sign2024project.reporttest.service.ReportTestService;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.apache.poi.ss.usermodel.VerticalAlignment;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

/**
 * 测试Controller
 *
 * @author ruoyi
 * @date 2024-07-04
 */
//@Api(tags = "测试")
@RestController
@RequestMapping("/api/reportTest")
public class ReportTestController {


    @Autowired
    private ReportTestService reportTestService;

    /**
     * 导出测试列表
     */
//    @Log(title = "测试", businessType = BusinessType.EXPORT)
//    @ApiOperation(value = "测试excel导出", notes = "测试excel导出")
//    @PostMapping("/export")
////    @GetMapping("/export")
//    public void export(HttpServletResponse response) throws IOException {
//        ReportTest reportTest = new ReportTest();
//        System.out.println(reportTest);
//        List<ReportTest> list = reportTestService.selectReportTestList(reportTest);
//        // 本地测试工具使用
//        String filename = "D:\\downloadAll\\excel\\评标专家单元格合并测试.xlsx";
////        EasyExcel.write(response.getOutputStream(), ReportTest.class)
////                .registerWriteHandler(new ReportTestWriteHandler(list))
////                .sheet("测试数据").doWrite(list);
//        EasyExcel.write(filename, ReportTest.class)
//                .registerWriteHandler(new ReportTestWriteHandler(list))
//                .sheet("测试数据").doWrite(list);
//    }

//    @ApiOperation(value = "测试excel导出", notes = "测试excel导出")
    @PostMapping("/export")
//    @GetMapping("/export")
    public void export(HttpServletResponse response) throws IOException {
        ReportTest reportTest = new ReportTest();
//        System.out.println(reportTest);
        List<ReportTest> list = reportTestService.selectReportTestList(reportTest);
        // 本地测试工具使用
//        String filename = "D:\\downloadAll\\excel\\评标专家单元格合并测试.xlsx";
        // 获取当前时间的毫秒值
        String filename = "D:\\downloadAll\\excel\\" + "评标专家单元格合并测试" + System.currentTimeMillis() + ".xlsx";


        // 头的策略
        WriteCellStyle headWriteCellStyle = new WriteCellStyle();
        // 背景设置为红色
        headWriteCellStyle.setFillForegroundColor(IndexedColors.WHITE1.getIndex());
        WriteFont headWriteFont = new WriteFont();
        headWriteFont.setFontHeightInPoints((short) 10);
        // 设置字体加粗
        headWriteFont.setBold(true);
        headWriteFont.setFontName("宋体");
        headWriteCellStyle.setWriteFont(headWriteFont);
        headWriteCellStyle.setHorizontalAlignment(HorizontalAlignment.CENTER);
        headWriteCellStyle.setVerticalAlignment(VerticalAlignment.CENTER);


        // 内容的策略
        WriteCellStyle contentWriteCellStyle = new WriteCellStyle();
//        contentWriteCellStyle.setFillPatternType(FillPatternType.SOLID_FOREGROUND);
        // 背景绿色
        contentWriteCellStyle.setFillForegroundColor(IndexedColors.WHITE1.getIndex());
        WriteFont contentWriteFont = new WriteFont();
        // 字体大小
        contentWriteFont.setFontHeightInPoints((short) 10);
        contentWriteCellStyle.setWriteFont(contentWriteFont);
        contentWriteFont.setFontName("宋体");
        // 设置边框
//        contentWriteCellStyle.setBorderTop(BorderStyle.MEDIUM);
//        contentWriteCellStyle.setBorderBottom(BorderStyle.MEDIUM);
//        contentWriteCellStyle.setBorderLeft(BorderStyle.MEDIUM);
//        contentWriteCellStyle.setBorderRight(BorderStyle.MEDIUM);
        // 设置边框颜色
        contentWriteCellStyle.setTopBorderColor(IndexedColors.BLACK1.getIndex());
        contentWriteCellStyle.setBottomBorderColor(IndexedColors.BLACK1.getIndex());
        contentWriteCellStyle.setLeftBorderColor(IndexedColors.BLACK1.getIndex());
        contentWriteCellStyle.setRightBorderColor(IndexedColors.BLACK1.getIndex());
        // 设置字体居中
        contentWriteCellStyle.setHorizontalAlignment(HorizontalAlignment.CENTER);
        contentWriteCellStyle.setVerticalAlignment(VerticalAlignment.CENTER);

        // 这个策略是 头是头的样式 内容是内容的样式 其他的策略可以自己实现
        HorizontalCellStyleStrategy horizontalCellStyleStrategy =
                new HorizontalCellStyleStrategy(headWriteCellStyle, contentWriteCellStyle);

//        // 这里 需要指定写用哪个class去写，然后写到第一个sheet，名字为模板 然后文件流会自动关闭
//        EasyExcel.write(fileName, DemoData.class).registerWriteHandler(horizontalCellStyleStrategy).sheet("模板")
//                .doWrite(data());


//        EasyExcel.write(filename, ReportTest.class)
//                .registerWriteHandler(horizontalCellStyleStrategy)
//                .registerWriteHandler(new ReportTestWriteHandler(list))
//                .sheet("测试数据").doWrite(list);
//        EasyExcel.write(filename, ReportTest.class)
//                .registerWriteHandler(horizontalCellStyleStrategy)
//                .registerWriteHandler(new ReportTestWriteHandler(list))
//                .sheet("测试数据").doWrite(list);

        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
        String fileName = URLEncoder.encode("测试数据", "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");

        EasyExcel.write(response.getOutputStream(), ReportTest.class)
                .registerWriteHandler(horizontalCellStyleStrategy)
                .registerWriteHandler(new ReportTestWriteHandler(list))
                .sheet("测试数据").doWrite(list);
    }


    //    @ApiOperation(value = "测试excel导入", notes = "测试excel导入")
    @PostMapping("/importInfo")
//    @GetMapping("/importInfo")
    public void importInfo(MultipartFile file) throws IOException {
//        return EasyExcel.read(is).head(clazz).sheet().doReadSync();
//        public List<T> importEasyExcel(InputStream is) throws Exception {
//            return EasyExcel.read(is).head(clazz).sheet().doReadSync();
//        }

        // 表头在第一列 使用默认
//        InputStream inputStream = file.getInputStream();
//        List<ReportTest> list = EasyExcel.read(inputStream).head(ReportTest.class).sheet().doReadSync();
//        list.forEach(System.out::println);
//        System.out.println(list);

        // 表头不在第一列
        // .headRowNumber(4) 根据表头行数进行处理
        InputStream inputStream = file.getInputStream();
        List<ReportTest> list = EasyExcel.read(inputStream).head(ReportTest.class).sheet().headRowNumber(4).doReadSync();
        list.forEach(System.out::println);
        System.out.println(list);

        ArrayList<String> listEmpty = new ArrayList<>();
        if (StringUtils.isNotEmpty(listEmpty)) {
            System.out.println("我是空");
        }

        // 测试 将 excel 中的数据写入到数据库中
        if (StringUtils.isNotEmpty(list)) {
            for (ReportTest item : list) {
                if (StringUtils.isNotNull(item)) {
                    reportTestService.insert(item);
                }
            }
        }


        // 业务逻辑后续自己补充
    }


    @PostMapping("/testExport")
//    @ApiOperation(value = "测试模版", notes = "测试模版")
    public ResponseEntity<Resource> testExport(HttpServletResponse response) throws IOException {
        try {
            // 从 classpath 读取文件
            Resource resource = new ClassPathResource("static/111.xlsx");
            InputStream inputStream = resource.getInputStream();


            response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
            response.setCharacterEncoding("utf-8");
            // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
            String fileName = URLEncoder.encode("测试数据", "UTF-8").replaceAll("\\+", "%20");
//            response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
            response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");

            // 设置响应头
            HttpHeaders headers = new HttpHeaders();
            headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=111.xlsx");
            headers.add(HttpHeaders.CONTENT_TYPE, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");

            // 返回文件
            return new ResponseEntity<>(resource, headers, HttpStatus.OK);
        } catch (IOException e) {
            return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }


}
